import mongoose from "mongoose";
import { type editFileType, FilesType, UserType } from "./interface";
const uri =
  "mongodb://ye:20030713@dds-wz9f3456361740241854-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740246129-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740245108-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740247406-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740248273-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740244748-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740243990-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740242419-pub.mongodb.rds.aliyuncs.com:3717,dds-wz9f3456361740249796-pub.mongodb.rds.aliyuncs.com:3717/StoreIt?replicaSet=mgset-86824073";
// const uri =
//   "mongodb+srv://h2799484803:sq5QGRuRn5oRR8dT@cluster0.ziowk.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
async function connectDB() {
  try {
    console.log("开始连接 MongoDB...");

    await mongoose.connect(uri, {
      connectTimeoutMS: 3000,
      socketTimeoutMS: 4500,
    });

    console.log("MongoDB 连接成功");
  } catch (error) {
    console.error("MongoDB 连接失败:", error);
    process.exit(1);
  }
}

// 连接数据库
connectDB();

var Schema = mongoose.Schema;

var UserSchema = new Schema(
  {
    fullName: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    accountId: {
      type: String,
      required: true,
    },
    avatar: String,
  },
  {
    timestamps: true,
  }
);
var FilesSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      enum: ["document", "image", "video", "audio", "other"],
      required: true,
    },
    bucketFileId: {
      type: String,
      required: true,
    },
    accountId: {
      type: String,
      required: true,
    },
    extension: String,
    size: Number,
    users: [String],
    owner: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
  },
  { timestamps: true }
);

var UserOperate = mongoose.model("User", UserSchema);
var FilesOperate = mongoose.model("Files", FilesSchema);

//新增用户
export const addUser = async (data: UserType) => {
  return await UserOperate.create(data);
};

// 查询用户
export const findUser = async (
  email: string,
  accountId?: string
): Promise<boolean | Object> => {
  try {
    let res = null;
    if (accountId) res = await UserOperate.findOne({ email, _id: accountId });
    else res = await UserOperate.findOne({ email });
    if (res) {
      return res; // 如果找到了用户
    } else {
      return false; // 如果没有找到用户
    }
  } catch (err) {
    console.log(err);
    return false; // 如果发生错误，返回 false
  }
};

//添加文件
export const addFile = async (data: FilesType) => {
  return await FilesOperate.create(data);
};

//查询文件
export const findFile = async (
  accountId: string,
  email: string,
  options?: {
    types?: string[]; // 文件类型
    searchText?: string; // 文件名的关键字搜索
    sort?: string; // 排序规则（如 `createdAt-desc`）
    limit?: number; // 查询条数
  }
) => {
  try {
    // 确保 accountId 是 ObjectId 类型
    const accountObjectId = new mongoose.Types.ObjectId(accountId);

    // 构建查询条件
    const query: any = {
      $or: [{ owner: accountObjectId }, { users: email }],
    };

    // 处理 `types` 条件（确保数组不为空）
    if (Array.isArray(options?.types) && options.types.length > 0) {
      query.type = { $in: options.types };
    }

    // 处理 `searchText` 条件（忽略大小写模糊匹配）
    if (options?.searchText) {
      query.name = { $regex: new RegExp(options.searchText, "i") };
    }

    // 初始化查询构造器
    let queryBuilder = FilesOperate.find(query).populate("owner").lean();

    // 处理 `sort`（支持 `createdAt-desc` 或 `name-asc` 之类格式）
    if (options?.sort) {
      const [field, order] = options.sort.split("-");
      const sortOrder = order === "desc" ? -1 : 1;
      queryBuilder = queryBuilder.sort({ [field]: sortOrder });
    } else {
      queryBuilder = queryBuilder.sort({ createdAt: -1 }); // 默认按 `createdAt` 降序
    }

    // 处理 `limit`
    if (options?.limit) {
      queryBuilder = queryBuilder.limit(options.limit);
    }

    // 执行查询
    const files = await queryBuilder.exec();

    // 确保返回值始终为数组
    return Array.isArray(files) ? files : [];
  } catch (error) {
    console.error("查询文件失败:", error);
    return [];
  }
};

//修改文件名
export const reNameFile = async (bucketFileId: string, Newname: string) => {
  const result = await FilesOperate.updateOne(
    { bucketFileId: bucketFileId },
    { $set: { name: Newname } },
    { new: true } // 返回更新后的文件
  );

  console.log("Update Result:", result); // 打印返回结果

  return result;
};
//增加users
export const addUsers = async (bucketFileId: string, users: string[]) => {
  const result = await FilesOperate.updateOne(
    { bucketFileId: bucketFileId },
    { $addToSet: { users: { $each: users } } },
    { new: true } // 返回更新后的文件
  );
  return result;
};
//减少users
export const removeUsers = async (bucketFileId: string, users: string[]) => {
  const result = await FilesOperate.updateOne(
    { bucketFileId: bucketFileId },
    { $pull: { users: { $in: users } } },
    { new: true } // 返回更新后的文件
  );
  return result;
};
//查询是否有权限修改文件
export const ifFindFileById = async (
  bucketFileId: string,
  accountId: string,
  email: string,
  type: editFileType
) => {
  const option = { bucketFileId: bucketFileId };
  if (["reName"].includes(type)) option["owner"] = accountId;
  else if (["share", "delete"].includes(type))
    option["$or"] = [
      { owner: accountId }, // 正确匹配 ObjectId
      { users: { $in: [email] } }, // 或者 users 数组包含 email
    ];
  return await FilesOperate.findOne(option);
};

//删除文件
export const deleteFile = async (bucketFileId: string) => {
  //查找BucketFileId的文件
  return await FilesOperate.deleteOne({ bucketFileId: bucketFileId });
};

//获取文件大小
export const getFileSize = async (bucketFileId: string) => {
  const res = await FilesOperate.findOne({ bucketFileId: bucketFileId });
  return res.size || -1;
};

//获取用户当前存储的大小
export const getUserUsedCount = async (accountId: string) => {
  const res = await FilesOperate.find({ accountId: accountId });
  let size = 0;
  res.forEach((item) => {
    size += item.size;
  });
  return size;
};
